<template>
	<div class="community-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="filter-bar mb20">
				<el-radio-group v-model="filterType" @change="handleFilterChange">
					<el-radio-button label="all">全部动态</el-radio-button>
					<el-radio-button label="following">只看关注</el-radio-button>
				</el-radio-group>
			</div>
			<div class="post-area mb20">
				<el-input v-model="newPostContent" :rows="3" type="textarea" placeholder="分享你的想法..." maxlength="255" show-word-limit />
				<div class="post-actions mt10">
					<el-button type="primary" @click="handlePost">发布</el-button>
				</div>
			</div>

			<!-- 动态列表 -->
			<div class="post-list" ref="postListRef">
				<el-empty v-if="filteredPosts.length === 0" description="暂无相关动态" />
				<div v-for="post in filteredPosts" :key="post.shid" class="post-item mb20" :id="'post-' + post.shid">
					<el-card shadow="hover">
						<!-- 用户信息 -->
						<div class="user-info">
							<el-avatar :size="40" :src="post.user.photo" class="mr10" />
							<div>
								<div class="user-name">{{ post.user.username }}</div>
								<div class="post-time">{{ formatTime(post.date) }}</div>
							</div>
							<el-button v-if="!isFollowing(post.user.uid)" type="text" class="follow-btn" @click="handleFollow(post.user.uid)"> + 关注 </el-button>
						</div>

						<!-- 动态内容 -->
						<div class="post-content mt15 mb15">{{ post.content }}</div>

						<!-- 图片展示 -->
						<div v-if="post.images" class="post-images">
							<el-image v-for="(img, index) in post.images" :key="index" :src="img" :preview-src-list="post.images" fit="cover" class="post-image" />
						</div>

						<!-- 互动区域 -->
						<div class="interaction-area mt15">
							<el-button type="text" :icon="post.isLiked ? 'el-icon-star-on' : 'el-icon-star-off'" @click="handleLike(post.shid)">
								{{ post.like }} 赞
							</el-button>
							<el-button type="text" icon="el-icon-chat-dot-round" @click="showCommentInput(post.shid)"> {{ post.comments.length }} 评论 </el-button>
							<el-button type="text" icon="el-icon-share">分享</el-button>
						</div>

						<!-- 评论输入框 -->
						<div v-if="activeCommentPost === post.shid" class="comment-input mt10">
							<el-input v-model="newCommentContent" placeholder="写下你的评论..." size="small">
								<template #append>
									<el-button type="primary" @click="handleComment(post.shid)">发送</el-button>
								</template>
							</el-input>
						</div>

						<!-- 评论列表 -->
						<div v-if="post.comments.length > 0" class="comment-list mt10">
							<div v-for="comment in post.comments" :key="comment.scid" class="comment-item">
								<el-avatar :size="30" :src="comment.user.photo" class="mr10" />
								<div class="comment-content">
									<span class="comment-user">{{ comment.user.username }}</span>
									<span class="comment-text">{{ comment.content }}</span>
									<div class="comment-time">{{ formatTime(comment.date) }}</div>
								</div>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="systemDic">
import { reactive, ref, computed, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';

// 新增状态
const filterType = ref('all'); // 'all' | 'following'
const postListRef = ref<HTMLElement | null>(null);

// 计算属性 - 筛选后的动态列表
const filteredPosts = computed(() => {
	if (!state.postList || !Array.isArray(state.postList)) {
		return [];
	}

	let posts = [...state.postList];

	if (filterType.value === 'following') {
		posts = posts.filter((post) => post.user && state.followingList.includes(post.user.uid));
	}

	return posts;
});

// 筛选类型变化处理
const handleFilterChange = () => {
	state.tableData.param.pageNum = 1;
	scrollToTop();
};

// 滚动到顶部函数
const scrollToTop = () => {
	nextTick(() => {
		if (postListRef.value) {
			postListRef.value.scrollTo({
				top: 0,
				behavior: 'smooth',
			});
		}
	});
};

// 滚动到指定动态
const scrollToPost = (shid: number) => {
	nextTick(() => {
		const postElement = document.getElementById(`post-${shid}`);
		if (postElement && postListRef.value) {
			postListRef.value.scrollTo({
				top: postElement.offsetTop - 20,
				behavior: 'smooth',
			});
		}
	});
};

// 在发布动态后滚动到新发布的动态
const handlePost = () => {
	if (!newPostContent.value.trim()) {
		ElMessage.warning('请输入动态内容');
		return;
	}

	const newPost = {
		shid: Math.max(...mockPosts.map((p) => p.shid)) + 1,
		uid: currentUser.value.uid,
		content: newPostContent.value,
		cnt: 0,
		like: 0,
		date: new Date().toISOString(),
		user: currentUser.value,
		comments: [],
		isLiked: false,
	};

	state.postList.unshift(newPost);
	newPostContent.value = '';
	ElMessage.success('发布成功');

	// 滚动到新发布的动态
	scrollToPost(newPost.shid);
};

// 定义变量内容
const state = reactive<SysDicState>({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			pageNum: 1,
			pageSize: 10,
		},
	},
});
const mockUsers = [
	{
		uid: 1,
		username: '张三',
		password: '123456',
		vip: 1,
		photo: 'https://randomuser.me/api/portraits/men/1.jpg',
		age: 25,
		date: '2023-05-10 10:00:00',
	},
	{
		uid: 2,
		username: '李四',
		password: '123456',
		vip: 0,
		photo: 'https://randomuser.me/api/portraits/women/2.jpg',
		age: 22,
		date: '2023-05-11 11:00:00',
	},
	{
		uid: 3,
		username: '王五',
		password: '123456',
		vip: 1,
		photo: 'https://randomuser.me/api/portraits/men/3.jpg',
		age: 28,
		date: '2023-05-12 12:00:00',
	},
	{
		uid: 4,
		username: '赵六',
		password: '123456',
		vip: 0,
		photo: 'https://randomuser.me/api/portraits/women/4.jpg',
		age: 24,
		date: '2023-05-13 13:00:00',
	},
];

// 当前登录用户 (UID为5)
const currentUser = ref({
	uid: 5,
	username: '当前用户',
	photo: 'https://randomuser.me/api/portraits/men/5.jpg',
});

// 修改后的关注关系数据
const mockFollows = [
	// 当前用户关注了张三(UID:1)和李四(UID:2)
	{ fid: 1, followuid: 1, fanuid: 5, content: '', ctime: '2023-05-10 10:00:00' },
	{ fid: 2, followuid: 2, fanuid: 5, content: '', ctime: '2023-05-11 11:00:00' },
	// 其他人之间的关注关系
	{ fid: 3, followuid: 1, fanuid: 2, content: '', ctime: '2023-05-10 10:00:00' },
	{ fid: 4, followuid: 1, fanuid: 3, content: '', ctime: '2023-05-11 11:00:00' },
	{ fid: 5, followuid: 3, fanuid: 4, content: '', ctime: '2023-05-12 12:00:00' },
];

// 修改后的动态数据
const mockPosts = [
	{
		shid: 1,
		uid: 1, // 张三的动态
		content: '今天天气真好，出去走走~',
		cnt: 0,
		like: 5,
		date: '2023-05-15 09:00:00',
		images: ['https://picsum.photos/500/300?random=1', 'https://picsum.photos/500/300?random=2'],
	},
	{
		shid: 2,
		uid: 2, // 李四的动态
		content: '分享一首好听的歌给大家',
		cnt: 0,
		like: 8,
		date: '2023-05-15 10:30:00',
	},
	{
		shid: 3,
		uid: 3, // 王五的动态
		content: '新买的手机，拍照效果不错',
		cnt: 0,
		like: 12,
		date: '2023-05-16 14:15:00',
		images: ['https://picsum.photos/500/300?random=3'],
	},
	{
		shid: 4,
		uid: 4, // 赵六的动态
		content: '周末去哪里玩比较好呢？求推荐',
		cnt: 0,
		like: 3,
		date: '2023-05-17 16:45:00',
	},
	{
		shid: 5,
		uid: 5, // 当前用户自己的动态
		content: '这是我发布的第一条动态',
		cnt: 0,
		like: 0,
		date: '2023-05-18 09:00:00',
	},
];

// 评论数据
const mockComments = [
	{ scid: 1, shid: 1, uid: 2, content: '是啊，天气不错', date: '2023-05-15 09:30:00' },
	{ scid: 2, shid: 1, uid: 3, content: '我也想去', date: '2023-05-15 10:15:00' },
	{ scid: 3, shid: 2, uid: 1, content: '什么歌呀？', date: '2023-05-15 11:00:00' },
	{ scid: 4, shid: 3, uid: 4, content: '什么型号的手机？', date: '2023-05-16 15:30:00' },
	{ scid: 5, shid: 5, uid: 1, content: '欢迎加入！', date: '2023-05-18 09:30:00' },
];

const newPostContent = ref('');
const newCommentContent = ref('');
const activeCommentPost = ref(null);

// 格式化时间
const formatTime = (time) => {
	return dayjs(time).format('YYYY-MM-DD HH:mm');
};

// 初始化数据
const initData = () => {
	// 合并数据
	state.postList = mockPosts.map((post) => {
		const user = mockUsers.find((u) => u.uid === post.uid);
		const comments = mockComments
			.filter((c) => c.shid === post.shid)
			.map((comment) => {
				const commentUser = mockUsers.find((u) => u.uid === comment.uid);
				return {
					...comment,
					user: commentUser,
				};
			});
		return {
			...post,
			user,
			comments,
			isLiked: false,
			images: post.images || [],
		};
	});

	state.tableData.total = state.postList.length;
	state.followingList = mockFollows.filter((f) => f.fanuid === currentUser.value.uid).map((f) => f.followuid);
};

// 检查是否已关注
const isFollowing = (uid) => {
	return state.followingList.includes(uid);
};

// 处理关注
const handleFollow = (uid) => {
	if (isFollowing(uid)) {
		state.followingList = state.followingList.filter((id) => id !== uid);
		ElMessage.success('已取消关注');
	} else {
		state.followingList.push(uid);
		ElMessage.success('关注成功');
	}
};

// 处理点赞
const handleLike = (shid) => {
	const post = state.postList.find((p) => p.shid === shid);
	if (post) {
		post.isLiked = !post.isLiked;
		post.like += post.isLiked ? 1 : -1;
	}
};

// 显示评论输入框
const showCommentInput = (shid) => {
	activeCommentPost.value = activeCommentPost.value === shid ? null : shid;
};

// 处理评论
const handleComment = (shid) => {
	if (!newCommentContent.value.trim()) {
		ElMessage.warning('请输入评论内容');
		return;
	}

	const post = state.postList.find((p) => p.shid === shid);
	if (post) {
		const newComment = {
			scid: Math.max(...mockComments.map((c) => c.scid)) + 1,
			shid,
			uid: currentUser.value.uid,
			content: newCommentContent.value,
			date: new Date().toISOString(),
			user: currentUser.value,
		};

		post.comments.push(newComment);
		newCommentContent.value = '';
		activeCommentPost.value = null;
		ElMessage.success('评论成功');
	}
};

// // 分页方法
// const onHandleSizeChange = (val) => {
// 	state.tableData.param.pageSize = val;
// 	// 这里可以添加获取分页数据的逻辑
// };

// const onHandleCurrentChange = (val) => {
// 	state.tableData.param.pageNum = val;
// 	// 这里可以添加获取分页数据的逻辑
// };

// 初始化表格数据
const getTableData = () => {
	state.tableData.loading = true;
	const data = [];
	state.tableData.data = data;
	state.tableData.total = state.tableData.data.length;
	setTimeout(() => {
		state.tableData.loading = false;
	}, 500);
};
// 页面加载时
onMounted(() => {
	getTableData();
	initData();
});
</script>

<style scoped>
.community-container {
	max-width: 100%;
	margin: 0 auto;
}
.filter-bar {
	margin-bottom: 20px;
	padding-bottom: 15px;
	border-bottom: 1px solid #eee;
}

.post-list {
	max-height: calc(100vh - 300px);
	overflow-y: auto;
	padding-right: 10px;
}

/* 自定义滚动条 */
.post-list::-webkit-scrollbar {
	width: 6px;
}

.post-list::-webkit-scrollbar-track {
	background: #f1f1f1;
	border-radius: 3px;
}

.post-list::-webkit-scrollbar-thumb {
	background: #c1c1c1;
	border-radius: 3px;
}

.post-list::-webkit-scrollbar-thumb:hover {
	background: #a8a8a8;
}

.post-area {
	background-color: #f9f9f9;
	padding: 15px;
	border-radius: 4px;
}

.user-info {
	display: flex;
	align-items: center;
	position: relative;
}

.user-name {
	font-weight: bold;
}

.post-time {
	font-size: 12px;
	color: #999;
}

.follow-btn {
	position: absolute;
	right: 0;
}

.post-content {
	font-size: 15px;
	line-height: 1.5;
}

.post-images {
	display: flex;
	flex-wrap: wrap;
	gap: 10px;
	margin-top: 10px;
}

.post-image {
	width: 150px;
	height: 150px;
	border-radius: 4px;
	cursor: pointer;
}

.interaction-area {
	border-top: 1px solid #eee;
	padding-top: 10px;
}

.comment-list {
	border-top: 1px solid #eee;
	padding-top: 10px;
}

.comment-item {
	display: flex;
	margin-bottom: 10px;
}

.comment-content {
	flex: 1;
}

.comment-user {
	font-weight: bold;
	margin-right: 5px;
}

.comment-text {
	word-break: break-all;
}

.comment-time {
	font-size: 12px;
	color: #999;
	margin-top: 2px;
}
</style>
